# @Time     : 2025/4/28 11:36
# @Software : Python 3.10
# @About    :
from typing import IO, Optional, Union

from . import tags
from .parser import Parser
from .writer import DocxDocumentWriter


class Markdown2Docx(DocxDocumentWriter):
    def __init__(self, text: str, docx_template: Optional[Union[str, IO[bytes]]] = None,
                 ignore_empty: bool = True, strict: bool = False, remove_default_paragraph: bool = True):
        """
        Markdown2Docx

        Args:
            text: **str** MarkDown文档
            docx_template: **Optional[Union[str, IO[bytes]]]** *default=None* Word模版路径
            ignore_empty: **bool** *default=True* 是否忽略空行
            strict: **bool** *default=False* 严格解析模式
            remove_default_paragraph: **bool** *default=True* 清空模版文件内容
        """
        super().__init__(docx=docx_template, remove_default_paragraph=remove_default_paragraph)
        self._parser = Parser(text=text, strict=strict)
        self._ignore_empty = ignore_empty
        self._is_write = False

    @property
    def parser(self):
        """
        HTML结果

        Returns:

        """
        return self._parser

    @property
    def md(self):
        return self._parser.md

    @property
    def html(self):
        return self._parser.html

    @property
    def soup(self):
        return self._parser.soup

    def save(self, path_or_stream: Union[str, IO[bytes]]):

    # def _to_docx(self, ignore_empty: bool = True):
        """
        执行MarkDown文档到Word文档的转换

        Args:
            ignore_empty: **bool** *default=True* 忽略空行

        Returns:

        """
        if not self._is_write:
            for i in self._parser.iter_paragraphs():
                if isinstance(i, tags.Heading):
                    self.add_heading(i)
                elif isinstance(i, tags.Texts):
                    self.add_paragraph(i)
                elif isinstance(i, tags.OrderedList):
                    self.add_ordered_list_paragraph(i)
                elif isinstance(i, tags.UnorderedList):
                    self.add_unordered_list_paragraph(i)
                elif isinstance(i, tags.IntenseQuote):
                    self.add_quote_paragraph(i)
                elif isinstance(i, tags.Image):
                    self.add_picture(i)
                elif isinstance(i, tags.Table):
                    self.add_table(i)
                else:
                    if not self._ignore_empty:
                        self.add_paragraph(i.strip())
            self._is_write = True
        self._document.save(path_or_stream)
